﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LikeObmen.UI.Web.Code.Data;
using LikeObmen.UI.Web.Models.Home;

namespace LikeObmen.UI.Web.Code.BL
{
    public class LikeHelper
    {
        public long VkId { get; set; }
        private readonly LikeDataEntities _entities;

        public LikeHelper(long vkId)
        {
            VkId = vkId;
            _entities = new LikeDataEntities();
        }

        public void ChangeLikeCount(long id)
        {
            var like = _entities.Likes.SingleOrDefault(x => x.Id == id);
            if (like != null)
            {
                like.LikeCount++;
                _entities.SaveChanges();
            } 
        }

        public void ChangeLike(long id)
        {
            var like = _entities.Likes.SingleOrDefault(x => x.Id == id);
            var user = _entities.Users.Single(x => x.VkId == VkId);
            if(like!= null)
            {
                like.CurrentLike++;
                like.UserInLikes.Add(new UserInLike
                    {
                        Like = like,
                        User = user
                    });
                _entities.SaveChanges();
            }
        }

        public long SetLike(string url)
        {
            var user = _entities.Users.SingleOrDefault(x => x.VkId == VkId);
            if(user == null)
            {
                user = new User {VkId = VkId};
                _entities.Users.AddObject(user);
            }
            var like = _entities.Likes.SingleOrDefault(x => x.Url.ToLower() == url.ToLower());
            if(like == null)
            {
                like = new Like
                    {
                        Url = url,
                        User = user
                    };
                _entities.Likes.AddObject(like);
            }
            like.LikeCount = 50;
            _entities.SaveChanges();
            return like.Id;
        }

        public ClickModel GetLike()
        {
            return _entities.Likes.Where(
                    x => x.User.VkId != VkId 
                        && x.CurrentLike < x.LikeCount
                        && x.UserInLikes.All(u => u.User.VkId != VkId)
                )
                .OrderBy(x => Guid.NewGuid())
                .Select(x => new ClickModel
                    {
                        Id = x.Id,
                        Url = x.Url
                    }).FirstOrDefault();
        }

        public List<ClickModel> GetLikes()
        {
            return _entities.Likes.Where(x => x.User.VkId != VkId && x.CurrentLike < x.LikeCount)
                .OrderBy(x => Guid.NewGuid())
                .Select(x => new ClickModel
                    {
                        Id = x.Id,
                        Url = x.Url
                    })
                .Take(6).ToList();
        }
    }
}